package slidingWindow;

import java.util.Comparator;
import java.util.PriorityQueue;

public class MaxSlidingWindow {

    /**
     * LeetCode T239 滑动窗口最大值
     * @param args
     */
    public static void main(String[] args) {

    }

    /**
     * 使用优先队列解决问题
     * @param nums
     * @param k
     * @return
     */
    public int[] maxSlidingWindow(int[] nums, int k) {
        int len = nums.length;
        int[] res = new int[len - k + 1];
        if (len < k){
            return null;
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] != o2[0])
                    return o2[0] - o1[0];
                return o1[1] - o2[1];
            }
        });
        //进行初始化
        for (int i = 0; i < k; i++){
            queue.offer(new int[]{nums[i], i});
        }
        res[0] = queue.peek()[0];
        int index = 1;
        for (int i = k; i < len - k + 1; i++){
            queue.offer(new int[]{nums[i], i});
            int[] peek = queue.peek();
            while (peek[1] < i - k + 1){
                queue.poll();
                peek = queue.peek();
            }
            res[index] = peek[0];
            index++;
        }

        return res;
    }
}
